package com.woniu.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.woniu.entity.Menu;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.mapping.FetchType;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * <p>
 *  Mapper 接口
 * </p>
 *
 * @author hyl
 * @since 2022-08-28
 */
@Repository
public interface MenuMapper extends BaseMapper<Menu> {

    @Results(id = "menuMap", value = {
            @Result(id = true, property = "menuId", column = "menu_id"),
            @Result(property = "menuName", column = "menu_name"),
            @Result(property = "menuPid", column = "menu_pid"),
            @Result(property = "menuSrc", column = "menu_src"),
            @Result(property = "menuPic", column = "menu_pic"),
            @Result(property = "menuStatus", column = "menu_status"),
            @Result(property = "sonMenus", column = "menu_id", javaType = List.class,
                    many = @Many(select = "com.woniu.mapper.MenuMapper.getAllByPid", fetchType = FetchType.LAZY))
    })
    @Select("select * from menu where menu_pid = #{pid}")
    List<Menu> getAllByPid(int pid);
    @Select("select * from menu where menu_id = #{id}")
    Menu getById(int id);

    @Select("select * from menu")
    List<Menu> selectAll();

    @Delete("delete form menu where menu_id = #{id}")
    void delete(int id);

    @Select("select * from menu m , role_mid_menu rm " +
            "where m.menu_id = rm.menu_id " +
            "and rm.role_id = #{roleId}")
    @Results({
            @Result(id = true, property = "menuId", column = "menu_id"),
            @Result(property = "menuName", column = "menu_name"),
            @Result(property = "menuPid", column = "menu_pid"),
            @Result(property = "menuSrc", column = "menu_src"),
            @Result(property = "menuPic", column = "menu_pic"),
            @Result(property = "menuStatus", column = "menu_status"),
            @Result(property = "sonMenus", column = "{pid = m.menu_id , roleId = rm.role_id}", javaType = List.class,
                    many = @Many(select = "com.woniu.mapper.MenuMapper.getByPidAndRoleId", fetchType = FetchType.LAZY))
    })
    List<Menu> getByRoleId(int roleId);

    /**
     * 查询指定 角色id 的子菜单信息
     *
     * @param pid 父菜单id
     * @param roleId 角色id
     * @return 返回根据 父菜单id 和 角色id 查找到的其子菜单集合
     */
    @Select("SELECT * FROM menu m,role_mid_menu rmm WHERE m.menu_pid=rmm.menu_id AND rmm.role_id=#{roleId} AND m.menu_pid=#{pid}")
    List<Menu> getByPidAndRoleId(@Param("pid") int pid, @Param("roleId") int roleId);


    /**
     * 获取全部菜单信息
     *
     * @return 返回所以菜单的集合
     */
    @Select("select * from menu where menu_status = 'y' and menu_pid = 0")
    @ResultMap("menuMap")
    List<Menu> getAll();
}
